﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Sparrow.Web.Router
{
    public static class RequestExtension
    {
        public static WebRouter FindRouter(this HttpRequest request)
        {
            var startIndex = Configration.RootRouter.Length;
            var len = request.Path.EndsWith(".aspx",StringComparison.InvariantCulture) ? request.Path.Length - startIndex - 5 : request.Path.Length - startIndex;
            var url = request.Path.Substring(Configration.RootRouter.Length, len);

            
            
            var nodes = url.Split(new char[]{'/'},StringSplitOptions.RemoveEmptyEntries);

            var routers = Factory.Proivder.RootRouters();

            var router = routers.Where(i => i.Name == nodes[0]).FirstOrDefault();

            if (router == null)
            {
                throw new RouterNotFoundException();
            }
            else
            {
                for (var i = 1; i < nodes.Length; i++)
                {
                    var next = router.ChildRouters.Where(r => r.Name == nodes[i]).FirstOrDefault();
                    if (next == null)
                    {
                        router.Parameters = nodes.Where((v, index) => index >= i).Select(v => v).ToArray();
                        return router;
                    }
                    else
                    {
                        router = next;
                    }
                }

                return router;
            }

        }
    }
}
